package com.party.admin.biz.notify;

import com.party.admin.biz.quartz.IScheduleJobService;
import com.party.admin.biz.quartz.impl.SchsduleService;
import com.party.admin.utils.RealmUtils;
import com.party.common.utils.DateUtils;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.notify.Event;
import com.party.core.model.notify.NotifySysMessage;
import com.party.core.model.notify.NotifySysMessageMember;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.notify.INotifySysMessageMemberService;
import com.party.core.service.notify.INotifySysMessageService;
import com.party.notify.notifyPush.officialPartner.IOfficialPartnerNotifySendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 系统消息业务处理
 *
 * @author yifeng
 * @date 2018/6/25 0025
 * @time 下午 17:35
 */
@Service
public class SysMessageBizService {
    @Autowired
    private INotifySysMessageService notifySysMessageService;
    @Autowired
    private INotifySysMessageMemberService notifySysMessageMemberService;
    @Autowired
    private IOfficialPartnerNotifySendService officialPartnerNotifySendService;
    @Autowired
    private IScheduleJobService scheduleJobService;
    @Autowired
    private IMemberGroupService memberGroupService;

    /**
     * 保存重要通知
     *
     * @param sysMessage 消息
     * @param memberList 推送对象
     * @param sendTime   推送时间
     */
    public void saveBiz(NotifySysMessage sysMessage, List<String> memberList, Date sendTime) {
        String currentId = RealmUtils.getCurrentUser().getId();
        if (StringUtils.isNotEmpty(sysMessage.getContent())) {
            String content = StringUtils.escapeHtml4Iframe2Video(sysMessage.getContent().trim());
            sysMessage.setContent(content);
        }
        if (StringUtils.isEmpty(sysMessage.getId())) {
            sysMessage.setCreateBy(currentId);
            sysMessage.setUpdateBy(currentId);
            notifySysMessageService.insert(sysMessage);
        } else {
            notifySysMessageService.update(sysMessage);
        }
        if (sysMessage.getIsPushAll().equals(YesNoStatus.YES.getCode())) {
            memberList = memberGroupService.getAllPartnerIds();
        }
        this.insertMessageMember(sysMessage, memberList);

        if (sendTime.getTime() < System.currentTimeMillis()) {
            // 定时的时间小于当前时间, 则直接立即执行
            this.sendImportNotify(sysMessage.getId());
        } else {
            String cron = DateUtils.formatDate(sendTime, "s m HH d M ? yyyy");

            final String clazz = "quartzBizSendImportantNotify";
            final String method = "send";

            Event event = new Event();
            event.setWay(com.party.common.constant.Constant.EVENT_AUTO);
            event.setName(SchsduleService.JOB_SEND_IMPORTANT_NOTIFY);
            event.setCode(clazz);
            event.setType("4");
            event.setCronExpression(cron);
            event.setIsSync(0);
            event.setClassName(clazz);
            event.setMethod(method);
            scheduleJobService.dynamicInsert(event, sysMessage.getId(), SchsduleService.GROUP_SEND_IMPORTANT_NOTIFY, new ArrayList<>());
        }
    }

    /**
     * 再次推送业务
     *
     * @param sysMessage 消息
     * @param memberList 用户列表
     */
    public void saveSendAgainBiz(NotifySysMessage sysMessage, List<String> memberList) {
        String currentId = RealmUtils.getCurrentUser().getId();
        NotifySysMessage db = notifySysMessageService.get(sysMessage.getId());
        db.setCreateDate(new Date());
        db.setUpdateDate(new Date());
        db.setCreateBy(currentId);
        db.setUpdateBy(currentId);
        db.setSendTime(new Date());
        db.setIsPushAll(sysMessage.getIsPushAll());
        db.setId(null);
        notifySysMessageService.insert(db);

        if (sysMessage.getIsPushAll().equals(YesNoStatus.YES.getCode())) {
            memberList = memberGroupService.getAllPartnerIds();
        }
        this.insertMessageMember(db, memberList);
        this.sendImportNotify(db.getId());
    }

    /**
     * 定时推送重要通知消息
     *
     * @param sysMessageId 系统消息id
     */
    public void sendImportNotify(String sysMessageId) {
        List<NotifySysMessageMember> notifySysMessageMembers = notifySysMessageMemberService.findByMessageId(sysMessageId);
        List<String> memberList = LangUtils.transform(notifySysMessageMembers, input -> input.getMemberId());
        officialPartnerNotifySendService.sendImportantNotify(sysMessageId, memberList);
    }

    /**
     * 消息和用户的关系
     *
     * @param sysMessage 消息
     * @param memberList 用户集合
     */
    private void insertMessageMember(NotifySysMessage sysMessage, List<String> memberList) {
        for (String memberId : memberList) {
            NotifySysMessageMember messageMember = new NotifySysMessageMember();
            messageMember.setSysMessageId(sysMessage.getId());
            messageMember.setMemberId(memberId);
            notifySysMessageMemberService.insert(messageMember);
        }
    }

    /**
     * 删除消息
     *
     * @param id 消息id
     */
    public void deleteQuartz(String id) {
        notifySysMessageService.deleteLogic(id);

        // 移除定时器
        final String triggerName = SchsduleService.JOB_SEND_IMPORTANT_NOTIFY.concat(SchsduleService.SEND_SHORT_MESSAGE_LINE).concat(id);
        final String group = SchsduleService.GROUP_SEND_IMPORTANT_NOTIFY;
        scheduleJobService.removeTrigger(triggerName, group);
    }
}
